<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入支付金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择支付状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentType">
        <el-select v-model="queryParams.paymentType" placeholder="请选择支付方式" clearable>
          <el-option v-for="dict in paymentTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间排序" prop="orderByTime">
        <el-select v-model="queryParams.orderByTime" placeholder="请选择时间排序" clearable>
          <el-option label="创建时间降序" value="create_time desc" />
          <el-option label="创建时间升序" value="create_time asc" />
          <el-option label="支付时间降序" value="pay_time desc" />
          <el-option label="支付时间升序" value="pay_time asc" />
          <el-option label="更新时间降序" value="update_time desc" />
          <el-option label="更新时间升序" value="update_time asc" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否已删除" prop="isDeleted">
        <el-select v-model="queryParams.isDeleted" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="0" />
          <el-option label="已删除" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checksystem:paymentOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['checksystem:paymentOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checksystem:paymentOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['checksystem:paymentOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paymentOrderList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" min-width="60" />
      <el-table-column label="用户ID" align="center" prop="userId" min-width="80" />
      <el-table-column label="手机号" align="center" prop="phone" min-width="120" />
      <el-table-column label="订单号" align="center" prop="orderNo" min-width="180" show-overflow-tooltip />
      <el-table-column label="支付金额" align="center" prop="amount" min-width="100">
        <template #default="scope">
          <span class="amount">{{ scope.row.amount }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="paymentType" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.paymentType === 1 ? 'success' : 'primary'" effect="light">
            {{ formatPaymentType(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" min-width="120">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.status)">
            {{ formatStatus(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="套餐类型" align="center" prop="packageType" min-width="120" show-overflow-tooltip />
      <el-table-column label="套餐积分" align="center" prop="packagePoints" min-width="100">
        <template #default="scope">
          <span class="package-points">{{ scope.row.packagePoints }} 点</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐时长" align="center" prop="packageDuration" min-width="100" />
      <el-table-column label="支付时间" align="center" prop="payTime" min-width="160">
        <template #default="scope">
          <span>{{ formatPayTime(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="160">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['checksystem:paymentOrder:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checksystem:paymentOrder:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checksystem:paymentOrder:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="pagination-container"
    />

    <!-- 添加或修改支付订单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="paymentOrderRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="自动关联用户手机号" disabled />
          <div class="el-form-item-msg">手机号会根据用户ID自动关联，无需手动输入</div>
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="支付金额" prop="amount">
          <el-input-number v-model="form.amount" :precision="2" :min="0" :max="100000" placeholder="请输入支付金额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择支付方式" style="width: 100%">
            <el-option v-for="dict in paymentTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐类型" prop="packageType">
          <el-select v-model="form.packageType" placeholder="请选择套餐类型" style="width: 100%">
            <el-option label="标准套餐" value="标准套餐" />
            <el-option label="新用户专享" value="新用户专享" />
            <el-option label="限时特惠" value="限时特惠" />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐积分" prop="packagePoints">
          <el-input-number v-model="form.packagePoints" :min="0" :precision="0" placeholder="请输入套餐积分" style="width: 100%" />
        </el-form-item>
        <el-form-item label="套餐时长" prop="packageDuration">
          <el-input v-model="form.packageDuration" placeholder="请输入套餐时长，如：30天" />
        </el-form-item>
        <el-form-item label="支付平台交易号" prop="transactionId">
          <el-input v-model="form.transactionId" placeholder="请输入支付平台交易号" />
        </el-form-item>
        <el-form-item label="支付二维码链接" prop="qrCodeUrl">
          <el-input v-model="form.qrCodeUrl" type="textarea" placeholder="请输入支付二维码链接" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker 
            v-model="form.payTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择支付时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否删除" prop="isDeleted">
          <el-radio-group v-model="form.isDeleted">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog title="支付订单详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="订单ID">{{ orderDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ orderDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ orderDetail.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="订单号">{{ orderDetail.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="支付金额">{{ orderDetail.amount }} 元</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ formatPaymentType(orderDetail) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="statusTagType(orderDetail.status)">{{ formatStatus(orderDetail) }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <el-divider />
      
      <el-descriptions title="套餐信息" :column="2" border>
        <el-descriptions-item label="套餐类型">{{ orderDetail.packageType }}</el-descriptions-item>
        <el-descriptions-item label="套餐积分">{{ orderDetail.packagePoints }} 点</el-descriptions-item>
        <el-descriptions-item label="套餐时长">{{ orderDetail.packageDuration }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider />
      
      <el-descriptions title="支付信息" :column="2" border>
        <el-descriptions-item label="支付平台交易号">{{ orderDetail.transactionId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ formatPayTime(orderDetail) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(orderDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(orderDetail.updateTime) }}</el-descriptions-item>
        <el-descriptions-item :span="2" label="支付二维码链接">
          <div class="qr-code-container">
            <span>{{ orderDetail.qrCodeUrl || '-' }}</span>
            <div v-if="orderDetail.qrCodeUrl" class="qr-code-preview">
              <img :src="orderDetail.qrCodeUrl" alt="支付二维码" class="qr-code-image" />
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PaymentOrder">
import { listPaymentOrder, getPaymentOrder, delPaymentOrder, addPaymentOrder, updatePaymentOrder } from "@/api/checksystem/paymentOrder";
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance();

const paymentOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailOpen = ref(false);
const orderDetail = ref({});

// 状态和支付方式选项
const statusOptions = [
  { value: 0, label: "未支付" },
  { value: 1, label: "已支付" },
  { value: 2, label: "支付失败" },
  { value: 3, label: "已取消" }
];

const paymentTypeOptions = [
  { value: 1, label: "微信支付" },
  { value: 2, label: "支付宝支付" }
];

const data = reactive({
  form: {
    id: null,
    userId: null,
    phone: null,
    orderNo: null,
    amount: null,
    paymentType: null,
    status: null,
    packageType: null,
    packagePoints: null,
    packageDuration: null,
    transactionId: null,
    qrCodeUrl: null,
    payTime: null,
    isDeleted: 0
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    phone: null,
    orderNo: null,
    amount: null,
    paymentType: null,
    status: null,
    packageType: null,
    packagePoints: null,
    packageDuration: null,
    transactionId: null,
    isDeleted: null,
    orderByTime: "create_time desc" // 默认按创建时间降序
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "支付金额不能为空", trigger: "blur" },
      { type: 'number', message: "支付金额必须为数字", trigger: "blur" }
    ],
    paymentType: [
      { required: true, message: "请选择支付方式", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择订单状态", trigger: "change" }
    ],
    isDeleted: [
      { required: true, message: "请选择是否删除", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 格式化支付方式
function formatPaymentType(row) {
  if (!row || row.paymentType === undefined) return '-';
  return row.paymentType === 1 ? '微信支付' : row.paymentType === 2 ? '支付宝支付' : '未知';
}

// 格式化订单状态
function formatStatus(row) {
  if (!row || row.status === undefined) return '-';
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '支付失败',
    3: '已取消'
  };
  return statusMap[row.status] || '未知状态';
}

// 订单状态对应的标签类型
function statusTagType(status) {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  };
  return typeMap[status] || 'info';
}

// 格式化日期时间
function formatDateTime(time) {
  if (!time) return '-';
  return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}');
}

// 格式化支付时间（特殊处理，因为payTime可能为null）
function formatPayTime(row) {
  if (!row) return '-';
  
  // 如果payTime为null但status为已支付，则使用updateTime作为支付时间
  if (row.status === 1 && !row.payTime) {
    return formatDateTime(row.updateTime) + " (订单更新时间)";
  }
  
  return formatDateTime(row.payTime);
}

/** 查询支付订单列表 */
function getList() {
  loading.value = true;
  listPaymentOrder(queryParams.value).then(response => {
    paymentOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 查看订单详情
function handleDetail(row) {
  const id = row.id;
  getPaymentOrder(id).then(response => {
    orderDetail.value = response.data;
    detailOpen.value = true;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    phone: null,
    orderNo: null,
    amount: null,
    paymentType: null,
    status: null,
    packageType: null,
    packagePoints: null,
    packageDuration: null,
    transactionId: null,
    qrCodeUrl: null,
    payTime: null,
    isDeleted: 0
  };
  proxy.resetForm("paymentOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 生成随机订单号
  const now = new Date();
  const timestamp = now.getTime().toString();
  const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
  form.value.orderNo = timestamp + random;
  form.value.status = 0; // 默认未支付
  form.value.isDeleted = 0; // 默认未删除

  open.value = true;
  title.value = "添加支付订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPaymentOrder(_id).then(response => {
    form.value = response.data;
    // 确保数据类型正确
    form.value.amount = Number(form.value.amount);
    form.value.packagePoints = Number(form.value.packagePoints);
    form.value.paymentType = Number(form.value.paymentType);
    form.value.status = Number(form.value.status);
    form.value.isDeleted = Number(form.value.isDeleted);
    
    open.value = true;
    title.value = "修改支付订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paymentOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePaymentOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPaymentOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除支付订单编号为"' + _ids + '"的数据项？').then(function() {
    return delPaymentOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checksystem/paymentOrder/export', {
    ...queryParams.value
  }, `paymentOrder_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 16px;
}

.pagination-container {
  padding: 10px 0;
  text-align: right;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
}

.package-points {
  font-weight: bold;
  color: #409eff;
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.qr-code-preview {
  max-width: 150px;
  max-height: 150px;
}

.qr-code-image {
  width: 100%;
  height: auto;
  border: 1px solid #eee;
  border-radius: 4px;
}

.el-divider {
  margin: 20px 0;
}

.el-form-item-msg {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
